/**
 * 部署 pay-server、pay-batch
 */

const shell = require('shelljs');// 引入shell.js等依赖
const func = require('./../util/func.js');

/**生成管理后台jar包到部署目录
 * 
 * @param {*} project_name 项目名称
 * @param {*} git_address 源代码地址
 * @param server_webapp_dir pay-server的jar的部署目录
 * @param batch_webapp_dir pay-batch的jar的部署目录
 * @returns 项目源代码根目录
 */
async function pay(src_path, git_address, server_webapp_dir,batch_webapp_dir) {
    const project_root = func.gitProjectName(git_address);

    const project_root_dir = src_path + "/" + project_root;//项目路径

    func.deleteDir(project_root_dir);//如果旧代码存在，则删除

    //第一步，摘取代码
    const clone_code = await func.git_clone(src_path, git_address);
    if (clone_code != 0) {
        console.log('拉取代码失败 ');
        shell.echo('克隆失败，请检查克隆地址是否存在');
        shell.exit(1);
    }

    //第二步，生成jar包
    const build_code = await func.bulid_jar(project_root_dir);
    if (build_code != 0) {
        console.log('构建jar包失败 ');
        shell.echo('构建jar包失败');
        shell.exit(1);
    }

    //第三步，复制到部署目标
    //pay-server
    const pay_server_dir= project_root_dir+"/server";
    const server_jar = pay_server_dir + '/target/' + func.pom_jar_name(pay_server_dir);
    console.info(server_jar);
    shell.rm('-rf',server_webapp_dir+"/*")
    const server_cpResult = shell.cp('-rf', server_jar, server_webapp_dir);
    console.info(new Date()+" cp code="+server_cpResult.code + (server_cpResult.code == 0 ? "成功" : "失败") + "复制jar包");

    //pay-batch
    const pay_batch_dir= project_root_dir+"/batch";
    const batch_jar = pay_batch_dir + '/target/' + func.pom_jar_name(pay_batch_dir);
    console.info(batch_jar);
    shell.rm('-rf',batch_webapp_dir+"/*")
    const batch_cpResult = shell.cp('-rf', batch_jar, batch_webapp_dir);
    console.info(new Date()+" cp code="+batch_cpResult.code + (batch_cpResult.code == 0 ? "成功" : "失败") + "复制jar包");

    return project_root_dir;
}

/**
 * 复制spring的yml配置文件到部署目录
 * @param {*} project_dir 源代码目录
 * @param {*} yml 配置文件名称
 * @param {*} target_dir 部署的目标目录
 */
 function copy_config(project_dir, yml, target_dir) {
    const config = project_dir + "/src/main/resources/"+yml;
    const target = target_dir + "/"+yml;
    if(shell.test('-f',target)){
        shell.rm('-r', target);
    }
    const cpResult = shell.cp('-rf', config, target);
    console.info((cpResult.code == 0 ? "成功" : "失败") + "\n复制" + config + "\n到" + target);
}

module.exports = {
    pay,
    copy_config
}


//测试 pay_admin_web
function test(){
    // sudo rm -rf /deploy/src/pay
    const src_path='/deploy/src';
    const git_address='https://fanruifeng:taijun432@git.visioners.cn/charge/pay.git';
    const server_webapp_dir='/deploy/pay_server/webapp',batch_webapp_dir='/deploy/pay_batch/webapp';
    pay(src_path, git_address, server_webapp_dir,batch_webapp_dir);
}

test();